﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MsmqNs = System.Messaging;

using WorkStation.Frameworks.EasyBus.MessageQueue;

namespace WorkStation.Frameworks.EasyBus.MessageQueue.Msmq
{
    /// <summary>
    /// MSMQ 通道实现
    /// </summary>
    public class MsmqChannel : ChannelBase
    {
        protected MsmqEndpoint _endpoint;
        protected MsmqNs.MessageQueue _queue;

        public MsmqChannel(MsmqEndpoint endpoint) 
        {
            this._endpoint = endpoint;

            this._queue = this.GetQueue();
        }

        public override void WriteMsg(Message msg)
        {
            this._queue.Send(msg);
        }

        public override Message ReadMsg()
        {

            MsmqNs.Message msg = null;

            try
            {
                msg = this._queue.Receive(new TimeSpan(0, 0, 0, 5)) as MsmqNs.Message;
            }
            catch (MsmqNs.MessageQueueException ce)
            {
                if (ce.MessageQueueErrorCode != MsmqNs.MessageQueueErrorCode.IOTimeout) { throw ce; }
            }

            if (msg != null)
            {
                return msg.Body as Message;
            }

            return null;
        }

        public override void Dispose()
        {
            if (this._queue != null) 
            {
                this._queue.Dispose();
            }
        }

        protected virtual MsmqNs.MessageQueue GetQueue() 
        {
            MsmqNs.MessageQueue queue = new MsmqNs.MessageQueue(this._endpoint.Address);

            queue.DefaultPropertiesToSend.Recoverable = true;
            queue.Formatter = new MsmqNs.XmlMessageFormatter(new Type[] { typeof(Message) });
            
            return queue;
        }
    }
}
